<script setup>
import { ref } from 'vue'
import { useCategoryAddService, useCategoryUpdateService } from '@/api/category.js'
import { ElMessage } from 'element-plus'
const title = ref('')
const dialogFormVisible = ref(false)
const form = ref({})
const formRef = ref()
const emit = defineEmits(['updateCategory'])

const onConfirm = async () => {
  await formRef.value.validate()
  if (form.value.id) {
    await useCategoryUpdateService(form.value)
  } else {
    await useCategoryAddService(form.value)
  }
  dialogFormVisible.value = false
  emit('updateCategory')
  ElMessage.success('操作成功')
}
const open = (data) => {
  dialogFormVisible.value = true
  if (Object.keys(data).length > 0) {
    form.value = { ...data }
    title.value = '修改分类'
  } else {
    form.value = {}
    title.value = '新增分类'
  }
}
defineExpose({
  open
})
</script>

<template>
  <el-dialog v-model="dialogFormVisible" :title="title" width="500">
    <el-form :model="form" ref="formRef">
      <el-form-item label="分类名称" label-width="auto" :rules="[{ required: true }]">
        <el-input v-model="form.categoryName" />
      </el-form-item>
      <el-form-item label="分类别名" label-width="auto" :rules="[{ required: true }]">
        <el-input v-model="form.categoryAlisa" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="onConfirm"> Confirm </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>
